package contactbook.dao.impl;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import contactbook.dao.ContactDAOInterface;
import contactbook.model.Contact;

@Stateless
@Local(ContactDAOInterface.class)
public class ContactDAO implements ContactDAOInterface {
	
	private static final String GET_CONTACTS_BY_NAME = "SELECT DISTINCT c FROM Contact c WHERE c.account.id = :ownerId AND c.firstName LIKE :firstName AND c.lastName LIKE :lastName";
	private static final String GET_CONTACTS_WITHOUT_GROUP = "SELECT DISTINCT c FROM Contact c WHERE c.group.id IS NULL AND c.account.id = :ownerId";
	
	@PersistenceContext(unitName = "ContactBookPU")
	protected EntityManager em;
		
	public ContactDAO() {}
	
	@Override
	public Contact addContact(Contact contact) {
		em.persist(contact);
		return contact;
	}

	@Override
	public void delete(int contactId) {
		Contact contact = em.find(Contact.class, contactId);
		em.remove(contact);
	}

	@Override
	public Contact findById(int contactId) {
		return em.find(Contact.class, contactId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Contact> findByName(int ownerId, String firstName, String lastName) {
		Query q = em.createQuery(GET_CONTACTS_BY_NAME);
		q.setParameter("ownerId", ownerId);
		q.setParameter("firstName", firstName);
		q.setParameter("lastName", lastName);
		return q.getResultList();
	}
	

	@SuppressWarnings("unchecked")
	@Override
	public List<Contact> getContactsWithoutGroup(int ownerId) {
		Query q = em.createQuery(GET_CONTACTS_WITHOUT_GROUP);
		q.setParameter("ownerId", ownerId);
		return q.getResultList();
	}
	
	@Override
	public void update(Contact contact) {
		try {
			em.merge(contact);
			em.flush();
		}
		catch(Exception ex) {	
		}
	}
	
	@Override
	public void setEntityManager(EntityManager em) {
		this.em = em;
	}
	
}
